import { FC, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import type { StateType } from "@/store";
import { TodoItemType, addTodo, delTodo, toggleTodo } from "@/store/demo/todoList";
import { Button, Checkbox, Form, Input } from "antd";
import styled from "styled-components";

const Container = styled.ul`
  width: 600px;
  min-height: 400px;
  margin: 20px auto;
  padding: 10px;
  background-color: #eee;
  & > li {
    min-height: 44px;
    padding: 10px;
    margin-bottom: 10px;
    background-color: #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 5px;
    &:nth-child(even) {
      background-color: #fff;
    }
    &:hover {
      button {
        display: block;
      }
    }
    button {
      display: none;
    }
  }
`;

const FormContainer = styled(Form)`
  text-align: center;
  width: 600px;
  margin: 0px auto;
  padding-top: 20px;
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
  input {
    height: 32px;
    width: 100%;
    padding: 0px 5px;
    border-radius: 5px;
    &:focus-visible {
      outline: none;
    }
  }
`;
const TodoList: FC = () => {
  const [keyword, setKeyword] = useState("");
  const dispatch = useDispatch();
  const list = useSelector<StateType>((state) => state.todoList) as TodoItemType[];
  const handleAdd = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (["Enter", "NumpadEnter"].includes(e.code)) {
      const newTodo = { id: Date.now() + "", title: keyword, completed: false };
      dispatch(addTodo(newTodo));
      setKeyword("");
    }
  };
  const onChange = (id: string) => {
    dispatch(toggleTodo({ id }));
  };
  const remove = (id: string) => {
    dispatch(delTodo({ id }));
  };
  return (
    <FormContainer>
      <Input
        type="text"
        value={keyword}
        onChange={(e) => setKeyword(e.target.value)}
        onKeyDown={handleAdd}
      />
      <Container>
        {list.map((t) => {
          return (
            <li key={t.id}>
              <div>
                <Checkbox checked={t.completed} onChange={() => onChange(t.id)} />
                <span>
                  {t.id}-{t.title}
                </span>
              </div>
              <Button size="small" danger onClick={() => remove(t.id)}>
                删除
              </Button>
            </li>
          );
        })}
      </Container>
    </FormContainer>
  );
};

export default TodoList;
